const AnyProxy = require('anyproxy');
const Sesame = require('./sesame');

module.exports.startProxy = async (clientIP)=>{
    global.sesame = new Sesame(mydb, clientIP);
    const options = {
        port: 5090,
        rule: require('./deal'),
        webInterface: {
            enable: false
        },
        dangerouslyIgnoreUnauthorized:true,
        // throttle: 10000,
        forceProxyHttps: false,
        silent: true
    };
    const proxyServer = new AnyProxy.ProxyServer(options);
    if (!AnyProxy.utils.certMgr.ifRootCAFileExists()) {
        AnyProxy.utils.certMgr.generateRootCA((error, keyPath) => {
            // let users to trust this CA before using proxy
            if (!error) {
                const certDir = require('path').dirname(keyPath);
                console.log('The cert is generated at', certDir);
                // const isWin = /^win/.test(process.platform);
                // if (isWin) {
                //     exec('start .', { cwd: certDir });
                // } else {
                //     exec('open .', { cwd: certDir });
                // }
            } else {
                console.error('error when generating rootCA', error);
            }
        });
    }
    proxyServer.start();
    await sesame.timing(true);
};
